﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web;
using System.IO;
using IpQuery;
using System.Collections.Specialized;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Net.Sockets;

namespace IpSolution
{
    class Program
    {
        static void Main(string[] args)
        {
            // TestOne();
            //TestTwo();
            // GetIpFromUrl();
            //TestUri();
            //PingTest();

            IpOperate.TestOne();
            Console.Read();
        }
        private static void TestUri()
        {
            ////string url = "http://baidu.com/asdf?name=张 三"; //baidu.com
            //string url = "http://m.baidu.com.cn/asdf?name=张 三"; //m.baidu.com.cn
            //Uri uri = new Uri(url);
            //Console.WriteLine(uri.Host);
        }
        public static void TestTwo()
        {
            Ip_BaiDu _ip = new Ip_BaiDu();
            //IpData_Baidu data = _ip.LoadData("119.162.11.124");
            //Console.WriteLine(JsonConvert.SerializeObject(data));

            List<IpData_Baidu> list = _ip.LoadList("119.162.11.124,118.184.180.46,192.30.253.113");
            Console.WriteLine(JsonConvert.SerializeObject(list));
        }
        public static void GetIpFromUrl()
        {
            string url = "https://www.baidu.com/";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Console.WriteLine(resp.Server);
            //获取请求地址的ip信息
            string host = req.Host;
            Uri uri = req.Address;
            WebHeaderCollection webheaders = req.Headers;

            TcpClient tcp = new TcpClient();


            HttpRequest req2 = new HttpRequest("", url, "");
            string type = req2.RequestType;
            NameValueCollection serValues = req2.ServerVariables;

            //HttpContext
            // HttpWorkerRequest

            //WebClient 


            ////使用Dns获取ip地址可能会有多个
            //Console.WriteLine("--------DNS获取--------");
            //IPAddress[] addres = Dns.GetHostAddresses(host);
            //foreach (var item in addres)
            //{
            //    Console.WriteLine(item.ToString());
            //}
            ////使用ping 命令获取IP地址,缺点如果远程服务器不允许ping的情况下会获取失败
            //Console.WriteLine("--------Ping命令获取--------");
            //Ping p1 = new Ping();
            //PingReply reply = p1.Send(host); //发送主机名或Ip地址
            //if (reply.Status == IPStatus.Success)
            //{
            //    Console.WriteLine(string.Format("Address: {0} ", reply.Address.ToString()));
            //}

            //CS应用获取客户端ip地址
            //RemoteEndpointMessageProperty endpointProperty = 
            //    OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] 
            //    as RemoteEndpointMessageProperty;

        }

        /// <summary>  
        /// 服务器端获取客户端请求IP和客户端机器名称  
        /// </summary>  
        public static void GetClientInfo()
        {
            //OperationContext context = OperationContext.Current;
            //MessageProperties messageProperties = context.IncomingMessageProperties;
            //RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            //HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            //string clientIp = !string.IsNullOrEmpty(requestProperty.Headers["X-Real-IP"]) ? requestProperty.Headers["X-Real-IP"] : endpointProperty.Address;
            //string clientName = Environment.MachineName;
            //Console.WriteLine("ClientIp: " + clientIp + "clientName:" + clientName);
        }
        public static void TestOne()
        {
            //排序的连接地址
            //请求地址
            // https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=119.162.11.124&co=&resource_id=6006&t=1478145571872&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110204481323950024978_1478145442947&_=1478145442951
            //相应内容
            // jQuery110204481323950024978_1478145442947({ "status":"0","t":"1478145571872","set_cache_time":"","data":[{"location":"山东省济南市 联通", "titlecont":"IP地址查询", "origip":"119.162.11.124", "origipquery":"119.162.11.124", "showlamp":"1", "showLikeShare":1, "shareImage":1, "ExtendedLocation":"", "OriginQuery":"119.162.11.124", "tplt":"ip", "resourceid":"6006", "fetchkey":"119.162.11.124", "appinfo":"", "role_id":0, "disp_type":0}]});
            string ip = "119.162.11.124";   //山东省济南市 联通
                                            //string ip = "118.184.180.46"; //江苏省常州市 电信
                                            //string ip = "192.30.253.113"; //美国
            string url = string.Format(" https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={0}&co=&resource_id=6006&t=1478145571872&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110204481323950024978_1478145442947&_=1478145442951", ip);

            //获取返回内容
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            string result = "";
            //注意，此处使用的编码是：gb2312
            //using (StreamReader reader = new StreamReader(stream, Encoding.Default))
            using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312")))
            {
                result = reader.ReadToEnd();
            }
            //去除json的函数名称
            int start = result.IndexOf("{");
            int end = result.LastIndexOf("}");
            string temp = result.Substring(start, end - start + 1);
            Console.WriteLine(temp);
            //解析Json结果
            JObject obj = JObject.Parse(temp);
            JArray data = obj["data"] as JArray;
            if (data != null)
            {
                JObject dataObj = data[0] as JObject;
                Console.WriteLine(dataObj["location"]);
            }
        }
        public static void PingTest()
        {
            //string host = "www.baidu.com";
            //Process p = new Process(); p.StartInfo.FileName = "cmd.exe";//设定程序名
            //p.StartInfo.UseShellExecute = false; //关闭Shell的使用
            //p.StartInfo.RedirectStandardInput = true;//重定向标准输入
            //p.StartInfo.RedirectStandardOutput = true;//重定向标准输出
            //p.StartInfo.RedirectStandardError = true;//重定向错误输出
            //p.StartInfo.CreateNoWindow = true;//设置不显示窗口
            //string pingrst; p.Start(); p.StandardInput.WriteLine("ping " + host); //主机或ip地址
            //p.StandardInput.WriteLine("exit");
            //string strRst = p.StandardOutput.ReadToEnd();
            //Console.WriteLine(strRst);
            //if (strRst.IndexOf("(0% loss)") != -1)
            //{
            //    pingrst = "连接";
            //}
            //else if (strRst.IndexOf("Destination host unreachable.") != -1)
            //{
            //    pingrst = "无法到达目的主机";
            //}
            //else if (strRst.IndexOf("Request timed out.") != -1)
            //{
            //    pingrst = "超时";
            //}
            //else if (strRst.IndexOf("Unknown host") != -1)
            //{
            //    pingrst = "无法解析主机";
            //}
            //else
            //{
            //    pingrst = strRst;
            //}
            //p.Close();


            ////------------使用ping类------
            //string host = "www.baidu.com";
            //Ping p1 = new Ping();
            //PingReply reply = p1.Send(host); //发送主机名或Ip地址
            //StringBuilder sbuilder;
            //if (reply.Status == IPStatus.Success)
            //{
            //    sbuilder = new StringBuilder();
            //    sbuilder.AppendLine(string.Format("Address: {0} ", reply.Address.ToString()));
            //    sbuilder.AppendLine(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
            //    sbuilder.AppendLine(string.Format("Time to live: {0} ", reply.Options.Ttl));
            //    sbuilder.AppendLine(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
            //    sbuilder.AppendLine(string.Format("Buffer size: {0} ", reply.Buffer.Length));
            //    Console.WriteLine(sbuilder.ToString());
            //}
            //else if (reply.Status == IPStatus.TimedOut)
            //{
            //    Console.WriteLine("超时");
            //}
            //else
            //{
            //    Console.WriteLine("失败");
            //}
        }
    }
}
